/*
 * @Author       : borfish
 * @Date         : 2025-08-08 10:42:22
 * @LastEditors  : borfish
 * @LastEditTime : 2025-08-08 11:25:43
 * @FilePath     : /src/commandcontroller.cpp
 * @Description  : 
 * Copyright 2025 OBKoro1, All Rights Reserved. 
 * 2025-08-08 10:42:22
 */

 #include "include/commandcontroller.h"
#include <QStringList>

CommandController::CommandController(MQTTHandler *mqttManager, QObject *parent)
    : QObject(parent), m_mqttManager(mqttManager)
{
}

void CommandController::executeCommand(const QString &command)
{
    QStringList parts = command.split(' ', QString::SkipEmptyParts);
    if(parts.isEmpty()) return;
    
    QString cmd = parts[0].toLower();
    
    if(cmd == "help") {
        showHelp();
    }
    else if(cmd == "connect") {
        if(parts.size() < 2) {
            emit newMessage("Usage: connect <host> [port=1883]");
            return;
        }
        QString host = parts[1];
        quint16 port = (parts.size() > 2) ? parts[2].toUShort() : 1883;
        m_mqttManager->connectToBroker(host, port);
    }
    else if(cmd == "disconnect") {
        m_mqttManager->disconnectFromBroker();
    }
    else if(cmd == "publish") {
        if(parts.size() < 3) {
            emit newMessage("Usage: publish <topic> <message>");
            return;
        }
        QString topic = parts[1];
        QString message = command.section(' ', 2);
        m_mqttManager->publish(topic, message);
    }
    else if(cmd == "subscribe") {
        if(parts.size() < 2) {
            emit newMessage("Usage: subscribe <topic>");
            return;
        }
        m_mqttManager->subscribe(parts[1]);
    }
    else if(cmd == "led") {
        if(parts.size() < 3) {
            emit newMessage("Usage: led <on/off>");
            return;
        }
        QString state = parts[1].toLower();
        if(state == "on" || state == "off") {
            m_mqttManager->publish("dev/board/led", state.toUpper());
        } else {
            emit newMessage("Invalid LED state. Use 'on' or 'off'");
        }
    }
    else {
        emit newMessage("Unknown command: " + cmd);
    }
}

void CommandController::showHelp()
{
    QString help = 
        "Available commands:\n"
        "  help                - Show this help\n"
        "  connect <host> [port] - Connect to MQTT broker\n"
        "  disconnect          - Disconnect from broker\n"
        "  publish <topic> <msg> - Publish message\n"
        "  subscribe <topic>   - Subscribe to topic\n"
        "  led <on/off>        - Control LED\n"
        "  exit                - Quit application";
    
    emit newMessage(help);
}